package com.mjk.common.tools.xml.conver.impl;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

import java.util.HashMap;
import java.util.Map;

public class MapConverter implements Converter {
    @Override
    public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContext context) {
//        Map.Entry<String, Object> entry = (Map.Entry<String, Object>) o;
//        writer.addAttribute("type", entry.getKey());
//        if (entry.getValue() != null) {
//            writer.setValue(entry.getValue().toString());
//        }
    }

    @Override
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        Map<String, String> map = new HashMap<>();
        while (reader.hasMoreChildren()) {
            reader.moveDown();
            String key = reader.getNodeName();
            String value = reader.getValue();
            map.put(key, value);
            reader.moveUp();
        }
        return map;
    }

    @Override
    public boolean canConvert(Class aClass) {
        return aClass.equals(HashMap.class);
    }
}
